package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.controller.Rst;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import com.jiedeng.util.ForwardConstants;
import com.jiedeng.util.SessionUtil;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目管理
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/projectManage")
public class ProjectManageController {
    @Value("${config.http.client.url}")
    public String url;
    @Autowired
    CommonComponent commonComponent;
    /**
     * 项目管理首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/projectManageUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String taskManageUI(Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            model.addAttribute("personPostId", ((Person) SessionUtil.getUserSession()).getPostId());

            //model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/projectHome";
    }

    /**
     * 项目开工
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/projectStartUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String projectStartUI(Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            Rst rst = commonComponent.checkModuleRule("1020100");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            model.addAttribute("dataUrl", url);
            model.addAttribute("today", DatetimeUtil.getDate());
            Map map = new HashMap<>();
            //首页左边菜单
            String ret = HttpClientHelper.postRequest2(url + "/multi/eps/all", map, "utf-8", "");
            List<EpsTree> menus = JSON.parseObject(ret.trim(), new TypeReference<List<EpsTree>>() {
            });
            model.addAttribute("treeMenu", menus);
            String ret2 = HttpClientHelper.postRequest2(url + "/multi/zone/all", map, "utf-8", "");
            List<ZoneTree> zoneTreeList = JSON.parseObject(ret2.trim(), new TypeReference<List<ZoneTree>>() {
            });
            model.addAttribute("zoneTreeList", zoneTreeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/projectStart";
    }

    /**
     * 新增项目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("addProject")
    public String addProject() {
        try {
            Map map = new HashMap();
            map.put("caption", SessionUtil.getPara("caption"));
            map.put("cap", SessionUtil.getPara("cap"));
            map.put("projectCode", SessionUtil.getPara("projectCode"));
            map.put("stime", SessionUtil.getPara("stime"));
            map.put("etime", SessionUtil.getPara("etime"));
            map.put("epsId", SessionUtil.getPara("epsId"));
            map.put("proTypeId", SessionUtil.getPara("proTypeId"));
            map.put("proDegreeId", SessionUtil.getPara("proDegreeId"));
            //map.put("closeTime", SessionUtil.getPara("closeTime"));
            map.put("contactInfo", SessionUtil.getPara("contactInfo"));
            map.put("zoneId", SessionUtil.getPara("zoneId"));
            map.put("memo", SessionUtil.getPara("memo"));
            map.put("checker", SessionUtil.getPara("checker"));
            map.put("corpPropCorpIds", SessionUtil.getPara("corpPropCorpIds"));
            map.put("creater", SessionUtil.getUserIdSession());
            String ret = HttpClientHelper.postRequest2(url + "/projectManage/addProjectEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 项目完工
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/projectCompleteUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String projectCompleteUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        model.addAttribute("ctx", request.getContextPath());
        try {

            String ret = HttpClientHelper.doGet(url + "/projectManage/projectComplete?checker=" + SessionUtil.getUserIdSession());
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<ProjectDetails> projectList = new ArrayList<>();
            if (ret != null) {
                projectList = JSON.parseObject(ret.trim(), new TypeReference<List<ProjectDetails>>() {
                });
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("projectList", getProjectDetailsPage(projectList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", projectList.size());
            model.addAttribute("maxPage", projectList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + projectList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/projectComplete";
    }

    /**
     * 人员调配
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/staffingUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String staffingUI(Model model, HttpServletRequest request) {
        Rst rst = commonComponent.checkModuleRule("1020200");
        if(!"OK".equals(rst.getMsg())){
            return ForwardConstants.REDIRECT + "/jurisdictionBlank";
        }
        model.addAttribute("ctx", request.getContextPath());
        try {
            model.addAttribute("dataUrl", url);
            model.addAttribute("personId", SessionUtil.getUserIdSession());
            model.addAttribute("personCorpId", ((Person) SessionUtil.getUserSession()).getCorpId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/staffing";
    }

    /**
     * 项目详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/projectDetailsUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String projectDetailsUI(Model model, HttpServletRequest request, String projectId) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            model.addAttribute("dataUrl", url);
            model.addAttribute("personId", SessionUtil.getUserIdSession());
            model.addAttribute("projectId", projectId);
            model.addAttribute("personCorpId", ((Person) SessionUtil.getUserSession()).getCorpId());
            String ret = HttpClientHelper.doGet(url + "/projectManage/getProjectDetailsById?projectId=" + projectId);

            if (!StringUtils.isEmpty(ret)) {
                ProjectDetails projectDetails = JSON.parseObject(ret.trim(), new TypeReference<ProjectDetails>() {
                });
                model.addAttribute("ProjectDetails", projectDetails);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/projectDetails";
    }

    /**
     * 项目审核
     *
     * @param model
     * @param request
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/projectAuditingUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String projectAuditingUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        model.addAttribute("ctx", request.getContextPath());
        try {

            String ret = HttpClientHelper.doGet(url + "/projectManage/projectAuditing?checker=" + SessionUtil.getUserIdSession());
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<Project> projectList = new ArrayList<>();
            if (!StringUtils.isEmpty(ret)) {
                projectList = JSON.parseObject(ret.trim(), new TypeReference<List<Project>>() {
                });
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("projectList", getProjectPage(projectList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", projectList.size());
            model.addAttribute("maxPage", projectList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + projectList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/project/projectAuditing";
    }

    /**
     * 分页列表数据
     *
     * @param projects
     * @param page
     * @param pageSize
     * @return
     */
    public List<Project> getProjectPage(List<Project> projects, int page, int pageSize) {
        int beginNum = (page - 1) * pageSize;
        int endNum = 0;
        if ((page) * pageSize < projects.size()) {
            endNum = (page) * pageSize;
        } else {
            endNum = projects.size();
        }
        List<Project> projectList = new ArrayList<>();
        for (int i = beginNum; i < endNum; i++) {
            projectList.add(projects.get(i));
        }
        return projectList;
    }

    public List<ProjectDetails> getProjectDetailsPage(List<ProjectDetails> projects, int page, int pageSize) {
        int beginNum = (page - 1) * pageSize;
        int endNum = 0;
        if ((page) * pageSize < projects.size()) {
            endNum = (page) * pageSize;
        } else {
            endNum = projects.size();
        }
        List<ProjectDetails> projectList = new ArrayList<>();
        for (int i = beginNum; i < endNum; i++) {
            projectList.add(projects.get(i));
        }
        return projectList;
    }

    /**
     * 审核修改项目状态
     *
     * @param projectId
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping("auditingProject")
    public String auditingProject(String projectId, String status) {
        try {
            Map map = new HashMap();
            map.put("status", status);
            map.put("projectId", projectId);
            String ret = HttpClientHelper.postRequest2(url + "/projectManage/editProjectStatus", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 删除项目
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping("delProject")
    public String delProject(String projectId) {
        try {
            Map map = new HashMap();
            map.put("projectId", projectId);
            String ret = HttpClientHelper.postRequest2(url + "/projectManage/delProjectById", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 人员调配
     *
     * @param corpId
     * @param postPropPersonIds
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping("addPersonAllocation")
    public String addPersonAllocation(String corpId, String postPropPersonIds, String projectId) {
        try {
            Map map = new HashMap();
            map.put("projectId", projectId);
            map.put("corpId", corpId);
            map.put("postPropPersonIds", postPropPersonIds);
            String ret = HttpClientHelper.postRequest2(url + "/projectManage/addPersonAllocation", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }
}
